package com.self.task;

import java.util.concurrent.ConcurrentHashMap;

public class BusinessHandlerLoader {

    private static ConcurrentHashMap<String,BusinessHandler> className2HandlerMap = new ConcurrentHashMap<>();
    private static ConcurrentHashMap<Class,BusinessHandler> class2HandlerMap = new ConcurrentHashMap<>();

    public static BusinessHandler loadHandler(String handlerClass) {
        return loadHandler(handlerClass,null);
    }

    public static BusinessHandler loadHandler(String handlerClass,ClassLoader classLoader) {

        BusinessHandler businessHandler = className2HandlerMap.get(handlerClass);
        if(businessHandler != null) {
            return businessHandler;
        }

        ClassLoader loader = classLoader;
        if(loader == null) {
            loader = Thread.currentThread().getContextClassLoader();
            if(loader == null) {
                loader = BusinessHandlerLoader.class.getClassLoader();
            }
        }

        try {

            Class<?> targetClass = Class.forName(handlerClass,true,loader);
            if(targetClass != null) {
                businessHandler = class2HandlerMap.get(targetClass);
                if(businessHandler != null) {
                    return businessHandler;
                }

                businessHandler = getInstance(targetClass);

                BusinessHandler old = className2HandlerMap.putIfAbsent(handlerClass,businessHandler);
                if(old != null) {
                    return old;
                }
                old = class2HandlerMap.putIfAbsent(targetClass,businessHandler);
                if(old != null) {
                    return old;
                }

                return businessHandler;
            }

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static BusinessHandler getInstance(Class targetClass) {
        return null;
    }
}
